<template>
  <div class="w-full h-full">
    <mci-dialog
      v-model="visible"
      :title="title"
      width="1000"
      top="10vh"
      draggable
      :confirm-handle="handleConfirm"
      @close="handleClosed"
    >
      <div class="flex justify-center">
        <div class="w-1/2">
          <mci-steps :active="activeStep" finish-status="success">
            <mci-step title="聚合数据集配置" />
            <mci-step title="聚合数据集测试" />
          </mci-steps>
        </div>
      </div>
      <div style="height: 50vh; overflow-y: auto">
        <FormMode :mode="'edit'">
          <div v-show="activeStep === 0">
            <mci-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" label-position="top">
              <!-- 接口名称 -->
              <mci-row>
                <mci-col :span="24">
                  <mci-form-item label="接口名称" prop="dataModelName">
                    <mci-input
                      v-model="ruleForm.dataModelName"
                      type="text"
                      :min="INPUT_MIN_DATA_MODEL_NAME"
                      :max="INPUT_MAX_DATA_MODEL_NAME"
                      :placeholder="`请填写`"
                      style="width: calc(100% - 16px)"
                    />
                  </mci-form-item>
                </mci-col>
              </mci-row>

              <!-- 分组字段 -->
              <mci-row>
                <!-- 表名称 -->
                <mci-col :span="12">
                  <mci-form-item label="表名称" prop="tableID">
                    <mci-select
                      v-model="ruleForm.tableID"
                      :list="tableOptions"
                      placeholder="请选择"
                      style="width: calc(100% - 16px)"
                      :disabled="dataModelID"
                    />
                  </mci-form-item>
                </mci-col>
                <!-- 分组字段 -->
                <mci-col :span="12">
                  <mci-form-item label="分组字段" prop="columns">
                    <mci-select
                      v-model="ruleForm.columns"
                      :multiple="true"
                      class="w-full"
                      :disabled="dataModelID || !ruleForm.tableID"
                      :collapse-tags="true"
                      collapse-tags-tooltip
                      :max-collapse-tags="3"
                      style="width: calc(100% - 16px)"
                    >
                      <template #header>
                        <mci-checkbox v-model="checkAll" :indeterminate="true" @change="handleCheckAll"> 全选 </mci-checkbox>
                      </template>
                      <mci-option
                        v-for="option in columnOptions"
                        :key="option.varName"
                        :label="option.varLabel"
                        :value="option.varName"
                      />
                    </mci-select>
                  </mci-form-item>
                </mci-col>
              </mci-row>

              <!-- 聚合函数 -->
              <mci-row>
                <mci-col :span="24">
                  <mci-form-item label="聚合函数设置" prop="aggColumns">
                    <AggColumnsAdd
                      ref="aggColumnsAddRef"
                      :tableID="ruleForm.tableID"
                      :disabled="dataModelID || !ruleForm.tableID"
                      class="mt-4"
                      style="width: calc(100% - 16px)"
                    />
                  </mci-form-item>
                </mci-col>
              </mci-row>

              <!-- 参数设置 -->
              <mci-form-item label="参数设置" prop="parameters">
                <!-- <AddBtn btn-text="新增参数" @add="addParam" /> -->
                <ParametersAdd ref="parametersAddRef" class="mt-4" style="width: calc(100% - 16px)" />
              </mci-form-item>

              <!-- 条件设置 -->
              <!-- <mci-form-item label="条件设置" prop="conditions">
          <AddBtn btn-text="新增条件" @add="addCond" />
          <CondsAdd ref="condAddRef" />
        </mci-form-item> -->

              <!-- 条件设置 -->
              <mci-form-item label="条件设置" prop="conditions">
                <div class="w-full py-8 bg-fill-2 min-h-100 mt-4" style="width: calc(100% - 16px)">
                  <Conditions
                    ref="conditionsRef"
                    v-model="ruleForm.conditions"
                    :variable-options="variableOptions"
                    class="w-full"
                    :left-options="leftOptions"
                  />
                </div>
              </mci-form-item>
            </mci-form>
          </div>
          <div v-show="activeStep === 1" style="width: calc(100% - 16px)">
            <div class="py-8 flex flex-col">
              <TestReq :data="testReqData" @change="handleTestReqChange" />
              <div class="flex justify-end mt-8">
                <mci-button plain type="primary" @click="execute">执行</mci-button>
              </div>
            </div>
            <div>
              <TestRes :table-data="tesResTableData" :table-column="tesResTableColumn" />
            </div>
          </div>
        </FormMode>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <mci-button @click="visible = false">取消</mci-button>
          <mci-button v-show="activeStep" @click="last"> 上一步 </mci-button>
          <mci-button v-show="activeStep === 0" type="primary" @click="next"> 下一步 </mci-button>
          <mci-button v-show="activeStep === 1" type="primary" @click="handleConfirm"> 确定 </mci-button>
        </span>
      </template>
    </mci-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
// import { ElSpace } from 'element-plus';
import {
  MciDialog,
  MciButton,
  MciInput,
  MciForm,
  MciFormItem,
  MciSelect,
  MciOption,
  MciCol,
  MciRow,
  MciMessage,
  MciStep,
  MciSteps,
  MciCheckbox
} from '@/components/base';
import { FormMode } from '@/components/base/Form/mode';
import type { RuleForm, TableOption } from './data';
import { INPUT_MAX_DATA_MODEL_NAME, INPUT_MIN_DATA_MODEL_NAME, dataModelKey, AggColumns, VarType } from './data';
// import AddBtn from '../AddBtn/index.vue';
import AggColumnsAdd from '../AggColumnsAdd/index.vue';
import ParametersAdd from '../ParametersAdd/index.vue';
import TestReq from '../TestReq/index.vue';
import TestRes from '../TestRes/index.vue';
// import CondsAdd from '@/views/comps/condsAdd/index.vue';
import { Conditions } from '@/components/business/Conditions';

import {
  getTableList,
  getTableFields,
  postDataCfgAggAdd,
  postDataCfgAggUpdate,
  postDataCfgAggGet,
  postDataCfgAggExecute
} from '@/api/decision-engine';
import type {
  IGetTableListRes,
  IGetTableFieldsReq,
  IGetTableFieldsRes,
  IPostDataCfgAggAddReq,
  IPostDataCfgAggAddRes,
  IPostDataCfgAggUpdateReq,
  // IPostDataCfgAggUpdateRes,
  IPostDataCfgAggGetReq,
  IPostDataCfgAggGetRes,
  IPostDataCfgAggExecuteReq,
  IPostDataCfgAggExecuteRes
} from '@/api/decision-engine';
import { ILeft, IVariable } from '@/components/business/Conditions/type';
import { CheckboxValueType } from 'element-plus';

// const props = defineProps({
//   showAdd: Boolean
// });
const emit = defineEmits<{
  (e: 'closed'): void;
}>();

// const formMode = useFormMode();

onMounted(() => {});

const variableOptions = ref<IVariable[]>([]);
const leftOptions = ref<ILeft[]>([]);
const visible = ref(false);
const title = ref('新增聚合数据集');
const dataModelID = ref();
const handleClosed = () => {
  emit('closed');
};

const activeStep = ref(0);

// 表单
const ruleFormRef = ref<any>();
const ruleForm = reactive<RuleForm>({
  dataModelName: '',
  tableID: '',
  columns: [],
  aggColumns: [],
  parameters: [],
  conditions: {}
});
// 聚合函数校验
const validateAggColumns = (rule: any, value: any, callback: any) => {
  const { aggColumns } = aggColumnsAddRef.value?.getData();
  const isAllItemsValid = aggColumns?.every(
    (item: { alias: string | undefined; column: string | undefined; aggFunc: string | undefined }) =>
      item.alias !== undefined &&
      item.alias !== '' &&
      item.alias !== null &&
      item.column !== undefined &&
      item.column !== '' &&
      item.column !== null &&
      item.aggFunc !== undefined &&
      item.aggFunc !== '' &&
      item.aggFunc !== null
  );
  if (isAllItemsValid) {
    callback();
  } else {
    callback(new Error('请添加聚合函数'));
  }
};
// 条件校验
const validateConditions = (rule: any, value: any, callback: any) => {
  if (ruleForm.conditions && ruleForm.conditions.conditions && ruleForm.conditions.conditions.length) {
    callback();
  } else {
    callback(new Error('请添加条件'));
  }
};
const rules = reactive<any>({
  dataModelName: [
    { required: true, message: '请填写接口名称', trigger: 'blur' }
    // { required: true, validator: validateTarget, trigger: 'blur' }
  ],
  tableID: [
    { required: true, message: '请选择表', trigger: 'blur' }
    // { required: true, validator: validateTarget, trigger: 'blur' }
  ],
  parameters: [
    // { required: true, message: '请完成参数设置的必填内容', trigger: 'blur' }
  ],
  aggColumns: [{ required: true, validator: validateAggColumns, trigger: 'blur' }]
  // conditions: [{ required: true, validator: validateConditions, trigger: 'blur' }]
});
// 列
const checkAll = ref(false);
const handleCheckAll = (val: CheckboxValueType) => {
  // indeterminate.value = false
  if (val) {
    ruleForm.columns = columnOptions.value.map((_) => _.varName);
  } else {
    ruleForm.columns = [];
  }
};
const tableOptions = ref<TableOption[]>([]);
const columnOptions = ref<TableOption[]>([]);

const parametersAddRef = ref<any>(null);
const aggColumnsAddRef = ref<any>(null);
// const condAddRef = ref<any>(null);
// 条件
const conditionsRef = ref<any>();
// const addParam = () => {
//   parametersAddRef.value?.addRow();
// };

// const addCond = () => {
//   condAddRef.value?.addRow();
// };

// 表格数据请求
const tableRequest = async () => {
  const data: IGetTableListRes = await getTableList();
  if (data) {
    tableOptions.value = data.map((item: string) => {
      return {
        label: item,
        value: item
      };
    });
  } else {
    tableOptions.value = [];
  }
};
tableRequest();

// 列
const columnRequest = async () => {
  if (!ruleForm.tableID) return;
  const params: IGetTableFieldsReq = {
    tableName: ruleForm.tableID
  };
  const data: IGetTableFieldsRes = await getTableFields(params);

  if (data) {
    columnOptions.value = data;
    leftOptions.value = data.map((item: any) => {
      return {
        label: item.varLabel ? item.varLabel : item.varName,
        value: item.varName
      };
    });
  }
};

watch(
  [() => ruleForm.tableID, () => ruleForm.parameters],
  ([tableID, parameters], [oldTableID]) => {
    if (tableID !== oldTableID) {
      if (!dataModelID.value) {
        ruleForm.columns = [];
      }
      tableID && columnRequest();
    }

    // if (columns && oldColumns && columns.join() !== oldColumns.join()) {
    //   leftOptions.value = columns.map((item: string) => {
    //     return {
    //       label: item,
    //       value: item
    //     };
    //   });
    // }
    if (parameters) {
      const arr = [];
      for (const iterator of parameters) {
        if (iterator && iterator.varName && iterator.varLabel) {
          arr.push({
            label: iterator.varLabel,
            value: iterator.varName
          });
        }
      }
      variableOptions.value = arr;
    }
  },
  { deep: true }
);

// 下一步
const next = () => {
  testReqData.value = [];
  const { parameters } = parametersAddRef.value?.getData();
  if (parameters) {
    testReqData.value = parameters.map((item: any) => {
      return {
        ...item,
        value: item.initValue || item.initValue === 0 ? item.initValue : ''
      };
    });
  }
  formValidate();
};

// 上一步
const last = () => {
  activeStep.value > 0 && activeStep.value--;
};

// 执行参数
const testReqData = ref([]);
const testReqResult = ref<any>([]);
// 执行返回
const tesResTableData = ref<any>([]);
const tesResTableColumn = ref<any>([]);

const handleTestReqChange = (value: any) => {
  testReqResult.value = value;
};

// 执行
const execute = () => {
  exeRequest();
};

// 执行请求
const exeRequest = async () => {
  const { conditions, conjs, splitIndexes } = ruleForm.conditions;

  const { parameters } = parametersAddRef.value?.getData();
  const { aggColumns } = aggColumnsAddRef.value?.getData();
  const { dataModelName, tableID, columns } = ruleForm;
  const paramsObj: any = {};
  if (testReqResult.value) {
    for (const iterator of testReqResult.value) {
      if (iterator) {
        paramsObj[iterator.varName] = iterator.value ? iterator.value : iterator.initValue;
      }
    }
  }
  const params: IPostDataCfgAggExecuteReq = {
    cfgName: dataModelName,
    tableName: tableID,
    // conditions: {
    //   conditions,
    //   conjs
    // },
    groupBy: columns,
    aggColumns,
    variables: parameters,
    params: paramsObj
  };
  if (conditions && conditions.length) {
    params.conditions = {
      conditions,
      conjs,
      splitIndexes
    };
  }

  const data: IPostDataCfgAggExecuteRes = await postDataCfgAggExecute(params);
  // 执行
  tesResTableData.value = [];
  tesResTableColumn.value = [];
  if (data) {
    const { results, variables } = data;
    if (results) tesResTableData.value = results;
    if (variables) {
      tesResTableColumn.value = variables.map((item: any) => {
        return {
          prop: item.varName,
          label: item.varLabel ? item.varLabel : item.varName
        };
      });
    }
  }
};

//  update参数
const updateParameters = (newVal: any) => {
  ruleForm.parameters = newVal;
};
provide(dataModelKey, { columnOptions, ruleForm, updateParameters });

const formValidate = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate((valid: any, fields: any) => {
    if (valid) {
      if (activeStep.value === 0) {
        activeStep.value === 0 && activeStep.value++;
      }
    } else {
      if (fields) {
        const keys = Object.keys(fields) || [];
        for (const key of keys) {
          if (key && fields[key]) {
            for (const item of fields[key]) {
              if (item && item.message) {
                MciMessage({
                  message: item.message,
                  type: 'warning'
                });
                return;
              }
            }
          }
        }
      }
    }
  });
};

// 新增请求
const addRequest = async () => {
  // const { conditions, conjs } = condAddRef.value?.getData();
  // const { conditions, conjs } = conditionsRef.value?.getData();
  const { conditions, conjs, splitIndexes } = ruleForm.conditions;

  const { parameters } = parametersAddRef.value?.getData();
  const { aggColumns } = aggColumnsAddRef.value?.getData();
  const { dataModelName, tableID, columns } = ruleForm;
  const params: IPostDataCfgAggAddReq = {
    cfgName: dataModelName,
    tableName: tableID,
    conditions: {
      conditions,
      conjs,
      splitIndexes
    },
    groupBy: columns,
    aggColumns,
    variables: parameters
  };
  console.log('🚀 ~ addRequest ~ params:', params);
  const data: IPostDataCfgAggAddRes = await postDataCfgAggAdd(params);
  // 新增成功
  visible.value = false;
};

// 修改请求
const modifyRequest = async () => {
  // const { conditions, conjs } = condAddRef.value?.getData();
  const { conditions, conjs, splitIndexes } = ruleForm.conditions;
  const { parameters } = parametersAddRef.value?.getData();
  const { dataModelName } = ruleForm;
  const params: IPostDataCfgAggUpdateReq = {
    id: dataModelID.value,
    cfgName: dataModelName,
    conditions: {
      conditions,
      conjs,
      splitIndexes
    },
    variables: parameters
  };
  postDataCfgAggUpdate(params).then(() => {
    visible.value = false;
  });
  // if (data) {
  // 修改成功
  // visible.value = false;
  // }
};

// 确定操作
const handleConfirm = () => {
  if (dataModelID.value) {
    modifyRequest();
  } else {
    addRequest();
  }
};

// 初始化
const initData = async (dataModel?: any) => {
  visible.value = true;
  dataModelID.value = dataModel?.id;
  activeStep.value = 0;
  tesResTableData.value = [];
  tesResTableColumn.value = [];
  // 回显
  if (dataModelID.value) {
    title.value = '修改聚合数据集';
    ruleForm.dataModelName = dataModel?.cfgName;
    // ruleForm.tableID = dataModel?.tableName;
    // ruleForm.columns = dataModel?.columns;
    // 从详情接口获取
    const params: IPostDataCfgAggGetReq = {
      id: dataModelID.value
    };

    const data: IPostDataCfgAggGetRes = await postDataCfgAggGet(params);
    if (data) {
      let arr: any[] = [];
      if (data?.variables) {
        arr = data.variables.filter((item) => item.scope === 'REQUEST')?.map((item) => {
            if (
              item &&
              item.initValue &&
              typeof item.initValue === 'string' &&
              (item.varType === VarType.Date || item.varType === VarType.DateTime)
            ) {
              item.initValue = parseInt(item.initValue);
            }
            return item;
            });

      }
      console.log('🚀 ~ initData ~ data:', data);
      aggColumnsAddRef.value?.initData(data.aggColumns);
      parametersAddRef.value?.initData(arr);
      // condAddRef.value?.initData(parseConditions, data?.conditions?.conjs);
      ruleForm.conditions = {
        conditions: data?.conditions?.conditions,
        conjs: data?.conditions?.conjs,
        splitIndexes: data?.conditions?.splitIndexes
      };
      ruleForm.columns = data.groupBy || [];
      ruleForm.aggColumns = data.aggColumns || [];

      if (data.tableName) {
        ruleForm.tableID = data.tableName;
        columnRequest();
      }
    }
  } else {
    title.value = '新增聚合数据集';
    // await nextTick();
    // await ruleFormRef?.value?.reset();
    ruleForm.dataModelName = '';
    ruleForm.tableID = '';
    ruleForm.columns = [];
    ruleForm.aggColumns = [];
    aggColumnsAddRef.value?.initData();
    parametersAddRef.value?.initData();
    // condAddRef.value?.initData();
    ruleForm.conditions = {};
  }
};

defineExpose({
  initData
});
</script>
